package com.tanjor.user.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.tanjor.user.entity.SysUser;
import com.tanjor.user.dubbo.dto.SysUserDTO;
import com.tanjor.user.mapper.SysUserMapper;
import com.tanjor.user.service.interfaces.ISysUserRoleService;
import com.tanjor.user.service.interfaces.ISysUserService;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.tanjor.common.datatable.ColumnFilter;
import com.tanjor.common.datatable.PageReq;
import com.tanjor.common.datatable.PageResp;
import com.tanjor.common.exception.BusinessException;
import com.tanjor.common.util.EncryptUtils;
import com.tanjor.common.util.ObjectUtil;
import com.tanjor.kafka.producer.KafkaService;
import com.tanjor.sys.dubbo.dto.SysRoleDTO;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.toolkit.IdWorker;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Liuwy
 * @since 2017-03-25
 */
@Service("SysUserServiceImpl")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
	
	@Resource(name="SysUserRoleServiceImpl")
	private ISysUserRoleService sysUserRoleService;
		
	@Resource(name="kafkaService")
	private KafkaService kafkaService;
	
	/**
	 *  List<SysUser> to List<SysUserDTO>
	 */
	private  List<SysUserDTO> copyList(List<SysUser> list){
		List<SysUserDTO> entityDTOs = new ArrayList<SysUserDTO>();
		if(list!=null){
			for(SysUser entity:list){
				SysUserDTO entityDTO = new SysUserDTO();
				ObjectUtil.copy(entity,entityDTO);
				entityDTOs.add(entityDTO);
			}
		}
		return entityDTOs;
	}
	
	/**
	 * 分页入参构造器
	 * @param pageReq
	 * @return
	 */
	private EntityWrapper<SysUser> createWrapper(PageReq pageReq){
		EntityWrapper<SysUser> wrapper = new EntityWrapper<SysUser>();
		if(pageReq.getColumnFilters()!=null){
			for(int i=0;i<pageReq.getColumnFilters().size();i++){
				ColumnFilter columnFilter = pageReq.getColumnFilters().get(i);
				wrapper.and(columnFilter.getName()+" "+columnFilter.getOprate()+" {"+i+"}", columnFilter.getValue());
			}
		}
		return wrapper;
	}
	
	@Override
	public PageResp findPage(PageReq pageReq) {
		// TODO Auto-generated method stub
		PageResp page = new PageResp();
		//请求标志位
		page.setDraw(pageReq.getDraw());
		//构造条件
		EntityWrapper<SysUser> wrapper = createWrapper(pageReq);
		Integer totalRows = this.baseMapper.selectCount(wrapper);
		if(StringUtils.isNotBlank(pageReq.getOrderBy())){
			wrapper.orderBy(pageReq.getOrderBy(), pageReq.getIsAsc());
		}
		//查询
		List<SysUserDTO> list = findPage(wrapper, pageReq.getStart(), pageReq.getLength());					
		//构造返回
		page.setData(list);
		page.setRecordsFiltered(totalRows);
		page.setRecordsTotal(totalRows);
		return page;
	}
	
	@Override
	public List<SysUserDTO> findPage(Wrapper<SysUser> wrapper,int start,int limit) {
		// TODO Auto-generated method stub
		List<SysUser> list = baseMapper.selectPage(new RowBounds(start, limit), wrapper);
		return this.copyList(list);
	}
	
	@Override
	public Map<String,Object> insert(SysUserDTO entityDTO) throws BusinessException{
		// TODO Auto-generated method stub	
		Map<String,Object> map = new HashMap<String,Object>();
		EntityWrapper<SysUser> wrapper = new EntityWrapper<SysUser>();
		wrapper.andNew("userno={0}", entityDTO.getUserno());
		int num = this.selectCount(wrapper);
		if(num==0){
			entityDTO.setId(""+IdWorker.getId());
			SysUser entity = new SysUser();
			ObjectUtil.copy(entityDTO,entity);
			//加权
			entity.setPassword(EncryptUtils.encodeMD5String(entityDTO.getId().substring(2,6)+entityDTO.getPassword()+entityDTO.getId().substring(11,14)));
			this.insert(entity);
			map.put("result", true);
		}else{
			map.put("result", false);
			map.put("msg", "账号"+entityDTO.getUserno()+"已经存在，请重新输入！");
		}
		return map;
	}
	
	@Override
	public Map<String,Object> update(SysUserDTO entityDTO) throws BusinessException{
		Map<String,Object> map = new HashMap<String,Object>();
		// TODO Auto-generated method stub
		SysUser entity = new SysUser();
		ObjectUtil.copy(entityDTO,entity);
		EntityWrapper<SysUser> wrapper = new EntityWrapper<SysUser>();
		wrapper.and("id={0}", entityDTO.getId());
		//加权
		if(StringUtils.isNotBlank(entity.getPassword())){
			entity.setPassword(EncryptUtils.encodeMD5String(entityDTO.getId().substring(2,6)+entityDTO.getPassword()+entityDTO.getId().substring(11,14)));
		}
		baseMapper.update(entity, wrapper);
		//entity.update(wrapper);
		map.put("result", true);
		return map;
	}
	
	@Override
	public SysUserDTO findById(Serializable id){
		// TODO Auto-generated method stub
		SysUserDTO entityDTO = new SysUserDTO();
		SysUser entity = this.selectById(id);
		ObjectUtil.copy(entity,entityDTO);
		return entityDTO;
	}

	@Override
	public Map<String,Object> login(String userNo, String password) throws BusinessException{
		// TODO Auto-generated method stub
		Map<String,Object> map = new HashMap<String, Object>();
		EntityWrapper<SysUser> wrapper = new EntityWrapper<SysUser>();
		wrapper.and("userno={0}", userNo);
		SysUser user = this.selectOne(wrapper);
		if(user==null){
			map.put("result", false);
			map.put("msg", "您输入的账号不存在!");
			return map;
		}
		String upwd = EncryptUtils.encodeMD5String(user.getId().substring(2,6)+password+user.getId().substring(11,14));
		if(!upwd.equals(user.getPassword())){
			map.put("result", false);
			map.put("msg", "您输入的密码不正确!");
			return map;
		}
		user.setPassword(null);//置空密码，避免泄露
		map.put("result", true);
		SysUserDTO entityDTO = new SysUserDTO();
		ObjectUtil.copy(user,entityDTO);
		map.put("sysuser", entityDTO);
		//获取系统用户角色
		SysRoleDTO sysRoleDTO = sysUserRoleService.findRoleByUserId(entityDTO.getId());
		map.put("sysrole", sysRoleDTO);
		//kafka登录日志
		kafkaService.sendMsg("demoTopic","登录成功");
		kafkaService.sendMsg("demoTopic1","登录成功1");
		kafkaService.sendMsg("demoTopic2","登录成功2");
		return map;
	}	
	
}
